package net.xdclass.controller;

import groovy.util.logging.Slf4j;
import net.xdclass.enums.ShortLinkStateEnum;
import net.xdclass.service.impl.ShortLinkServiceImpl;
import net.xdclass.util.CommonUtil;
import net.xdclass.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.concurrent.TimeUnit;


@Controller
@Slf4j
public class LinkApiController {
    @Autowired
	private ShortLinkServiceImpl shortLinkService;

	@GetMapping(path = "/{shortLinkCode}")
	public void dispatch(@PathVariable(name = "shortLinkCode") String shortLinkCode,
						 HttpServletRequest requeset,HttpServletResponse httpServletResponse){

		if (isLetterDigit(shortLinkCode)){
		ShortLinkVO  shortLinkVO = shortLinkService.getByShortLink(shortLinkCode);
		if(isVisitable(shortLinkVO)){
			String oringalUrl = shortLinkVO.getOriginalUrl();
			String newUrl = CommonUtil.removePrefix(oringalUrl);
			httpServletResponse.setHeader("Location",newUrl);
			httpServletResponse.setStatus(HttpStatus.FOUND.value());
		} else {
			httpServletResponse.setStatus(HttpStatus.NOT_FOUND.value());
            return;
		}
	}}

	private static boolean isVisitable(ShortLinkVO shortLinkVO){
	if(shortLinkVO.getExpired().getTime()> CommonUtil.getCurrentTimestamp()&&
			shortLinkVO != null	){
		if (ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState())) {
		return  true;}
	}else if ( shortLinkVO.getExpired().getTime() == -1 && shortLinkVO != null){
		if (ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState())) {
		return true; }
	}
		return false;
	}

	private static boolean isLetterDigit(String shortLinkCode){
		String regex = "^[0-9a-zA-Z]+$";
        return shortLinkCode.matches(regex);
	}
}

